const {emptyData,nowTime,postLogData} = require("../utils/misc")
const ObjectId = require('mongodb').ObjectId
const router = require('koa-router')();
const mongo = require('../compents/mongo')

router.prefix('/discoupondetail')

router.get('/list', async ctx => {
    postLogData("请求优惠券细节数据库")
   let where={}
    const res = await mongo.find('discoupondetail', {where})
    const total = res.length
    if (res) {
        ctx.body = { data: res, code: 20000, total, message: "数据请求成功" }
    } else {
        ctx.body = {data:res, code: 50001, message: "数据请求失败" }
    }
    
})

router.post('/save', async ctx => {
    postLogData("新增优惠券细节")
    let camData = ctx.request.body
    camData= emptyData(camData,["name","type","state","useTime","operate"])
    const res = await mongo.insertOne('discoupondetail', { ...camData,getTime:nowTime()})
    if (res.insertedId) {
        ctx.body = { data: res, code: 20000, message: "数据插入成功" };
    } else {
        ctx.body = { data: res, code: 50002, message: "数据插入失败" };
    }
})
// 修改数据库
router.post('/change', async ctx => {
    postLogData("修改优惠券细节")
    const { _id } = ctx.request.body
    const update = ctx.request.body
    delete update._id
    const res = await mongo.updateOne('discoupondetail', { where: { _id: ObjectId(_id) }, update })
    if (res.modifiedCount > 0) {
        ctx.body = { data: res, code: 20000, message: "数据修改成功" };
    } else {
        ctx.body = { data: res, code: 50004, message: "数据修改失败" };
    }
})

// 删除单挑数据
router.get('/delOne', async ctx => {
    postLogData("单删优惠券细节")
    const { _id } = ctx.query
    const res = await mongo.deleteOne('discoupondetail', { _id: ObjectId(_id) })
    if (res.deletedCount > 0) {
        ctx.body = { data: res, code: 20000, message: "数据删除成功" };
    } else {
        ctx.body = { data: res, code: 50005, message: "数据删除失败" };
    }
})
// 删除多条数据  
router.get('/delMany', async ctx => {
    postLogData("多删优惠券细节")
    let { ids } = ctx.query
    ids = JSON.parse(ids)
    console.log(ids);
    const res = await mongo.deleteMany('discoupondetail', ids)
    if (res.deletedCount > 0) {
        ctx.body = { data: res, code: 20000, message: "数据批量删除成功" };
    } else {
        ctx.body = { data: res, code: 50006, message: "数据批量删除失败" };
    }
})

module.exports = router 